// 图片轮播功能
function initImageSlider() {
    const slides = document.querySelectorAll('.slide-image');
    const thumbnails = document.querySelectorAll('.thumbnail');
    const indicators = document.querySelectorAll('.indicator');
    const prevBtn = document.getElementById('prevSlide');
    const nextBtn = document.getElementById('nextSlide');
    let currentIndex = 0;
    let slideInterval;

    // 显示指定索引的幻灯片
    function showSlide(index) {
        // 隐藏所有幻灯片
        slides.forEach(slide => slide.classList.remove('active'));
        thumbnails.forEach(thumb => thumb.classList.remove('active'));
        indicators.forEach(indicator => indicator.classList.remove('active'));

        // 显示当前幻灯片
        slides[index].classList.add('active');
        thumbnails[index].classList.add('active');
        indicators[index].classList.add('active');
        currentIndex = index;
    }

    // 下一张幻灯片
    function nextSlide() {
        let nextIndex = (currentIndex + 1) % slides.length;
        showSlide(nextIndex);
    }

    // 上一张幻灯片
    function prevSlide() {
        let prevIndex = (currentIndex - 1 + slides.length) % slides.length;
        showSlide(prevIndex);
    }

    // 自动播放
    function startSlideshow() {
        slideInterval = setInterval(nextSlide, 5000);
    }

    // 停止自动播放
    function stopSlideshow() {
        clearInterval(slideInterval);
    }

    // 事件监听
    prevBtn.addEventListener('click', () => {
        stopSlideshow();
        prevSlide();
        startSlideshow();
    });

    nextBtn.addEventListener('click', () => {
        stopSlideshow();
        nextSlide();
        startSlideshow();
    });

    // 缩略图点击事件
    thumbnails.forEach((thumb, index) => {
        thumb.addEventListener('click', () => {
            stopSlideshow();
            showSlide(index);
            startSlideshow();
        });
    });

    // 指示器点击事件
    indicators.forEach((indicator, index) => {
        indicator.addEventListener('click', () => {
            stopSlideshow();
            showSlide(index);
            startSlideshow();
        });
    });

    // 鼠标悬停时停止播放
    document.querySelector('.main-image-container').addEventListener('mouseenter', stopSlideshow);
    document.querySelector('.main-image-container').addEventListener('mouseleave', startSlideshow);

    // 初始化
    startSlideshow();
}

// 颜色选择功能
function initColorSelection() {
    const colorOptions = document.querySelectorAll('.color-option');
    colorOptions.forEach(option => {
        option.addEventListener('click', () => {
            // 移除所有活动状态
            colorOptions.forEach(opt => opt.classList.remove('active'));
            // 添加当前活动状态
            option.classList.add('active');
        });
    });
}

// 尺寸选择功能
function initSizeSelection() {
    const sizeOptions = document.querySelectorAll('.size-option');
    sizeOptions.forEach(option => {
        option.addEventListener('click', () => {
            // 移除所有活动状态
            sizeOptions.forEach(opt => opt.classList.remove('active'));
            // 添加当前活动状态
            option.classList.add('active');
        });
    });
}

// 数量选择器功能
function initQuantitySelector() {
    const decreaseBtn = document.getElementById('decreaseBtn');
    const increaseBtn = document.getElementById('increaseBtn');
    const quantityInput = document.getElementById('quantityInput');

    decreaseBtn.addEventListener('click', () => {
        let value = parseInt(quantityInput.value);
        if (value > 1) {
            quantityInput.value = value - 1;
        }
    });

    increaseBtn.addEventListener('click', () => {
        let value = parseInt(quantityInput.value);
        quantityInput.value = value + 1;
    });

    quantityInput.addEventListener('change', () => {
        let value = parseInt(quantityInput.value);
        if (isNaN(value) || value < 1) {
            quantityInput.value = 1;
        }
    });
}

// 购物车功能
function initShoppingCart() {
    const cartBtn = document.getElementById('cartBtn');
    const closeCart = document.getElementById('closeCart');
    const cartSidebar = document.getElementById('cartSidebar');
    const cartOverlay = document.getElementById('cartOverlay');
    const addToCartBtn = document.getElementById('addToCartBtn');
    const cartItemsContainer = document.getElementById('cartItems');
    const cartCount = document.getElementById('cartCount');
    const cartTotal = document.getElementById('cartTotal');
    
    let cart = JSON.parse(localStorage.getItem('cart')) || [];

    // 更新购物车显示
    function updateCart() {
        // 清空购物车容器
        cartItemsContainer.innerHTML = '';
        
        if (cart.length === 0) {
            cartItemsContainer.innerHTML = '<div class="empty-cart">购物车为空</div>';
            cartCount.textContent = '0';
            cartTotal.textContent = '0';
            return;
        }
        
        // 添加购物车项目
        cart.forEach((item, index) => {
            const cartItem = document.createElement('div');
            cartItem.className = 'cart-item';
            cartItem.innerHTML = `
                <img src="${item.image}" alt="${item.title}" class="cart-item-image">
                <div class="cart-item-details">
                    <div class="cart-item-title">${item.title}</div>
                    <div class="cart-item-options">颜色: ${item.color} | 尺寸: ${item.size}</div>
                    <div class="cart-item-price">¥${item.price} x ${item.quantity}</div>
                    <button class="cart-item-remove" data-index="${index}">移除</button>
                </div>
            `;
            cartItemsContainer.appendChild(cartItem);
        });
        
        // 更新购物车数量
        const totalItems = cart.reduce((sum, item) => sum + item.quantity, 0);
        cartCount.textContent = totalItems;
        
        // 更新购物车总价
        const totalPrice = cart.reduce((sum, item) => sum + (item.price * item.quantity), 0);
        cartTotal.textContent = totalPrice.toFixed(2);
        
        // 保存购物车到本地存储
        localStorage.setItem('cart', JSON.stringify(cart));
        
        // 添加移除按钮事件
        document.querySelectorAll('.cart-item-remove').forEach(button => {
            button.addEventListener('click', () => {
                const index = parseInt(button.getAttribute('data-index'));
                cart.splice(index, 1);
                updateCart();
                showNotification('商品已从购物车移除', 'error');
            });
        });
    }

    // 切换购物车显示
    function toggleCart() {
        cartSidebar.classList.toggle('open');
        cartOverlay.classList.toggle('visible');
        document.body.style.overflow = cartSidebar.classList.contains('open') ? 'hidden' : '';
    }

    // 添加商品到购物车
    addToCartBtn.addEventListener('click', () => {
        const title = document.querySelector('.product-title').textContent;
        const price = parseFloat(document.querySelector('.price').textContent);
        const quantity = parseInt(document.getElementById('quantityInput').value);
        const color = document.querySelector('.color-option.active').getAttribute('data-color');
        const size = document.querySelector('.size-option.active').getAttribute('data-size');
        const image = document.querySelector('.slide-image.active').src;
        
        // 检查是否已存在相同商品
        const existingItemIndex = cart.findIndex(
            item => item.title === title && item.color === color && item.size === size
        );
        
        if (existingItemIndex !== -1) {
            // 如果存在，增加数量
            cart[existingItemIndex].quantity += quantity;
        } else {
            // 如果不存在，添加新商品
            cart.push({
                title,
                price,
                quantity,
                color,
                size,
                image
            });
        }
        
        updateCart();
        showNotification(`已添加 ${quantity} 件商品到购物车`);
    });

    // 事件监听
    cartBtn.addEventListener('click', toggleCart);
    closeCart.addEventListener('click', toggleCart);
    cartOverlay.addEventListener('click', toggleCart);
    
    // 立即购买按钮
    document.getElementById('buyNowBtn').addEventListener('click', () => {
        // 先添加到购物车
        addToCartBtn.click();
        // 然后显示购物车
        setTimeout(() => {
            toggleCart();
        }, 500);
    });
    
    // 初始化购物车
    updateCart();
}

// 评价排序功能
function initReviewSorting() {
    const reviewSort = document.getElementById('reviewSort');
    const reviewsList = document.getElementById('reviewsList');
    const reviewItems = Array.from(reviewsList.querySelectorAll('.review-item'));
    
    reviewSort.addEventListener('change', () => {
        const sortType = reviewSort.value;
        let sortedReviews;
        
        switch (sortType) {
            case 'latest':
                // 按日期排序（最新的在前）
                sortedReviews = [...reviewItems].sort((a, b) => {
                    const dateA = new Date(a.querySelector('.review-date').textContent);
                    const dateB = new Date(b.querySelector('.review-date').textContent);
                    return dateB - dateA;
                });
                break;
            case 'highest':
                // 按评分排序（最高的在前）
                sortedReviews = [...reviewItems].sort((a, b) => {
                    const ratingA = a.querySelector('.review-rating').textContent.split('★').length - 1;
                    const ratingB = b.querySelector('.review-rating').textContent.split('★').length - 1;
                    return ratingB - ratingA;
                });
                break;
            case 'lowest':
                // 按评分排序（最低的在前）
                sortedReviews = [...reviewItems].sort((a, b) => {
                    const ratingA = a.querySelector('.review-rating').textContent.split('★').length - 1;
                    const ratingB = b.querySelector('.review-rating').textContent.split('★').length - 1;
                    return ratingA - ratingB;
                });
                break;
        }
        
        // 重新添加排序后的评价
        reviewsList.innerHTML = '';
        sortedReviews.forEach(review => reviewsList.appendChild(review));
    });
    
    // 加载更多评价按钮
    document.getElementById('loadMoreReviews').addEventListener('click', () => {
        showNotification('加载更多评价功能正在开发中');
    });
}

// 通知提示功能
function showNotification(message, type = 'success') {
    const notification = document.getElementById('notification');
    
    notification.textContent = message;
    notification.className = 'notification show';
    
    if (type === 'error') {
        notification.classList.add('error');
    }
    
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            notification.classList.remove('error');
        }, 300);
    }, 3000);
}

// 初始化所有功能
function init() {
    initImageSlider();
    initColorSelection();
    initSizeSelection();
    initQuantitySelector();
    initShoppingCart();
    initReviewSorting();
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', init);